package edu.gyc.security.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Random;
import java.util.concurrent.Callable;

@RestController
@Slf4j
public class AsyncController {
    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    @RequestMapping("/order")
    public DeferredResult<String > order( )throws Exception{
        log.info(Thread.currentThread().getName()+" Start.");
      /**  Callable<String > result=new Callable<String>() {
            @Override
            public String call() throws Exception {

                log.info(Thread.currentThread().getName()+" start.");
                Thread.sleep(2000);
                log.info(Thread.currentThread().getName()+" return.");
                return "下载异步线程完毕！";
            }
        };

        log.info(Thread.currentThread().getName()+" Return.");
        return result;
       **/
        String orderNumber = Math.round(new Random().nextDouble() * 100000) + "";

        mockQueue.setPlaceOrder(orderNumber);

        DeferredResult<String> result = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber, result);
        log.info(Thread.currentThread().getName()+" Return.");
        return result;
    }

}
